package org.Modulo3;
import org.Modulo1.*;
import org.Modulo2.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.DefaultListModel;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author javier
 */
public class Facturacion extends javax.swing.JFrame {

    DefaultListModel modeloListaPedTo = new DefaultListModel();

    /**
     * Creates new form Facturacion
     */
     Pedido p=new Pedido();
     Cliente c = new Cliente();
    
    public Facturacion() {
        initComponents();
        setLocationRelativeTo(null);
        
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
       
       jListPedTo.setModel(modeloListaPedTo);
       modeloListaPedTo.removeAllElements();
       p.getListaObjetos().clear();
        if (!Menu.eleForm) {
            Menu.eleForm = false;
            lblEstablecimiento.setText(Menu.txtEstablecimiento.getText());
            lblCliente.setText(Menu.txtApellido.getText() + ", " + Menu.txtNombre.getText());
            lblCIF.setText(Menu.txtCIF.getText());
            String[] fecha = Historial.jListPedidosCliente.getSelectedValue().toString().split(" ");
            lblDate.setText(fecha[0]);
            p.setFecha(Historial.jListPedidosCliente.getSelectedValue().toString());

            c.setCIF(lblCIF.getText());
            c.setNombre(Menu.txtNombre.getText());
            c.setApellido(Menu.txtApellido.getText());
            GestorClientes.buscarCliente(c);
            c.setEstablecimiento(Menu.txtEstablecimiento.getText());
            p.setCliente(c.getId());

            GestorPedido.buscarPedido(c, Historial.jListPedidosCliente.getSelectedValue().toString(), p);
            GestorPedido.cargarProdPed(p);

            for (int i = 0; i < p.getListaObjetos().size(); i++) {
                modeloListaPedTo.addElement(p.getListaObjetos().get(i).getCantidad() + " x " + p.getListaObjetos().get(i).getProducto().getDescripcion());
            }

            double precio = 0;
            for (int i = 0; i < p.getListaObjetos().size(); i++) {
                precio += p.getListaObjetos().get(i).getProducto().getPrecio() * p.getListaObjetos().get(i).getCantidad();
            }
            lblPrecioT.setText(String.valueOf(precio) + " €");
            
        } else {
             Date dnow = new Date();
               SimpleDateFormat datef = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
               String fecha = datef.format(dnow);
               String[]date=fecha.split(" ");
            String cliente=Menu.modelocmbCliente.getSelectedItem().toString();
            String[]nombre=cliente.split(", ");
            lblCliente.setText(cliente);

                for (int i = 0; i < GestorClientes.getListaClientes().size(); i++) {

                    if (nombre[0].equalsIgnoreCase(GestorClientes.getListaClientes().get(i).getApellido()) && nombre[1].equalsIgnoreCase(GestorClientes.getListaClientes().get(i).getNombre())) {
                        c.setNombre(nombre[1]);
                        c.setApellido(nombre[0]);
                        c.setCIF(GestorClientes.getListaClientes().get(i).getCIF());
                        c.setDireccion(GestorClientes.getListaClientes().get(i).getDireccion());
                        c.setEstablecimiento(GestorClientes.getListaClientes().get(i).getEstablecimiento());
                        c.setId(GestorClientes.getListaClientes().get(i).getId());
                        c.setTelefono(GestorClientes.getListaClientes().get(i).getTelefono());

                    }
                 }
                GestorClientes.buscarCliente(c);
                p.setCliente(c.getId());
                p.setFecha(fecha);

                lblEstablecimiento.setText(c.getEstablecimiento());
                lblCIF.setText(c.getCIF());
               
                lblDate.setText(date[0]);
            GestorPedido.buscarPedido(c,fecha, p);
            GestorPedido.cargarProdPed(p);

            for (int i = 0; i < p.getListaObjetos().size(); i++) {
                modeloListaPedTo.addElement(p.getListaObjetos().get(i).getCantidad() + " x " + p.getListaObjetos().get(i).getProducto().getDescripcion());
            }
            double precio = 0;
            for (int i = 0; i < p.getListaObjetos().size(); i++) {
                precio += p.getListaObjetos().get(i).getProducto().getPrecio() * p.getListaObjetos().get(i).getCantidad();
            }
            lblPrecioT.setText(String.valueOf(precio) + " €");
                
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblEstablecimiento = new javax.swing.JLabel();
        lblCliente = new javax.swing.JLabel();
        lblCIF = new javax.swing.JLabel();
        lblDate = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListPedTo = new javax.swing.JList();
        jLabel5 = new javax.swing.JLabel();
        lblPrecioT = new javax.swing.JLabel();
        jBtnImprimir = new javax.swing.JButton();
        btnBorrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Facturacion"); // NOI18N
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Establecimiento:");

        jLabel2.setText("Cliente:");

        jLabel3.setText("CIF:");

        jLabel4.setText("Fecha:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblCIF))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lblCliente)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblEstablecimiento)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblDate)
                        .addGap(97, 97, 97))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(lblEstablecimiento)
                    .addComponent(lblDate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lblCliente))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblCIF))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jListPedTo.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListPedTo.setEnabled(false);
        jScrollPane2.setViewportView(jListPedTo);

        jLabel5.setText("Total: ");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblPrecioT))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 514, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(lblPrecioT)))
        );

        jBtnImprimir.setText("Imprimir");
        jBtnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnImprimirActionPerformed(evt);
            }
        });

        btnBorrar.setText("Borrar");
        btnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnBorrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnImprimir))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(19, 19, 19))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnImprimir)
                    .addComponent(btnBorrar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarActionPerformed

        Historial.modeloListaPedCli.removeElement(p.getFecha());
        GestorPedido.getListaPedCli().remove(p);

        GestorPedido.eliPed(p);
        this.dispose();

    }//GEN-LAST:event_btnBorrarActionPerformed

    private void jBtnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnImprimirActionPerformed
       this.dispose();
        try{ 
            String nomFac=("Factura"+p.getId()+".txt");
       PrintWriter factura=new PrintWriter(new FileWriter("Factura"+p.getId()+".txt"));
       factura.println("Nº de Pedido: "+ p.getId());
       factura.println("Cliente: "+ c.getApellido()+", "+c.getNombre());
       factura.println("CIF: "+c.getCIF());
       factura.println("Establecimiento: "+ c.getEstablecimiento());
       factura.println("Fecha: " + p.getFecha());
       factura.println("---------------------------------------------------------------");
       for(int i=0;i<p.getListaObjetos().size();i++){
           factura.println(p.getListaObjetos().get(i).getCantidad() + " x " + p.getListaObjetos().get(i).getProducto().getDescripcion());
       }
     factura.println("---------------------------------------------------------------");

      factura.println("Total: "+lblPrecioT.getText());
      factura.close();
      Process proceso= Runtime.getRuntime().exec("notepad.exe "+nomFac);

       }catch (Exception e){
           
           
       }

    }//GEN-LAST:event_jBtnImprimirActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Facturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Facturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Facturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Facturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Facturacion().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBorrar;
    private javax.swing.JButton jBtnImprimir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JList jListPedTo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblCIF;
    private javax.swing.JLabel lblCliente;
    private javax.swing.JLabel lblDate;
    private javax.swing.JLabel lblEstablecimiento;
    private javax.swing.JLabel lblPrecioT;
    // End of variables declaration//GEN-END:variables
}

